package com.yang.security.token;

import com.yang.security.model.LoginUser;
import com.yang.security.user.CustomUsernamePasswordAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Created by baipan
 * Date: 2019-12-18
 * Token过滤器
 * 拦截所有请求
 */
@Component
@Slf4j
public class TokenFilter extends OncePerRequestFilter {


	@Autowired
	private TokenService tokenService;


	@Override
	protected void doFilterInternal(HttpServletRequest request,
									HttpServletResponse response,
									FilterChain filterChain) throws ServletException, IOException {
		log.debug(request.getRequestURI());
		String token = TokenHelper.getToken(request);
		if (StringUtils.isNotBlank(token)) {
			LoginUser loginUser = tokenService.getLoginUser(token);
			if (Objects.nonNull(loginUser)) {
				UsernamePasswordAuthenticationToken authentication = CustomUsernamePasswordAuthenticationToken.build(
						loginUser,
						null,
						loginUser.getAuthorities()
				);
				SecurityContextHolder.getContext().setAuthentication(authentication);
			}
		}

		filterChain.doFilter(request, response);
	}







}
